package com.atguigu.eduservice.controller.web;

import com.atguigu.common.R;
import com.atguigu.common.jwt.JwtUtils;
import com.atguigu.common.ordervo.CourseOrderWebVo;
import com.atguigu.eduservice.entity.tree.TreeEntity;
import com.atguigu.eduservice.entity.vo.CourseFrontVo;
import com.atguigu.eduservice.entity.vo.CourseWebVo;
import com.atguigu.eduservice.feign.OrderClient;
import com.atguigu.eduservice.service.EduChapterService;
import com.atguigu.eduservice.service.EduCourseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @Author panghl
 * @Date 2021/2/19 20:00
 * @Description TODO
 **/
@RestController
@RequestMapping("/eduservice/coursefront")
@Api(tags = "前端课程信息展示")
public class CourseFrontController {

    @Autowired
    private EduCourseService eduCourseService;

    @Autowired
    private EduChapterService eduChapterService;

    @Autowired
    private OrderClient orderClient;

    @ApiOperation(value = "条件查询带分页的课程信息")
    @PostMapping(value = "/getFrontCourseList/{page}/{limit}")
    public R getFrontCourseList(@PathVariable long page,
                                @PathVariable long limit,
                                @RequestBody(required = false)CourseFrontVo courseFrontVo){
        Map<String,Object> map = eduCourseService.getFrontCourseList(page,limit,courseFrontVo);
        return R.ok().data(map);
    }

    @ApiOperation(value = "课程详情")
    @GetMapping(value = "/getFrontCourseInfo/{courseId}")
    public R getFrontCourseInfo(@PathVariable String courseId, HttpServletRequest request){
        //根据课程id，编写sql语句查询课程信息
        CourseWebVo courseWebVo = eduCourseService.getBaseCourseInfo(courseId);
        List<TreeEntity> chapterVideoList = eduChapterService.getChapterVideoByCourseId(courseId);

        //远程调用，判断课程是否被购买
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        boolean isBuy = false;
        if (!StringUtils.isEmpty(memberId)){
            isBuy = orderClient.isBuyCourse(memberId, courseId);
        }

        return R.ok().data("courseWebVo",courseWebVo)
                .data("chapterVideoList",chapterVideoList)
                .data("isbuy",isBuy);
    }

    @ApiOperation(value = "根据课程id获取订单课程详情")
    @PostMapping(value = "/getCourseInfoOrder/{id}")
    public CourseOrderWebVo getCourseInfoOrder(@PathVariable String id){
        CourseWebVo courseWebVo = eduCourseService.getBaseCourseInfo(id);
        CourseOrderWebVo courseOrderWebVo = new CourseOrderWebVo();
        BeanUtils.copyProperties(courseWebVo,courseOrderWebVo);
        return courseOrderWebVo;
    }
}
